﻿using NLog;
using System;
using ZeroMQ;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Threading;
using System.Web.Routing;
using Web.Auction.Bid.Models;

namespace Web.Auction.Bid
{
    public class MvcApplication : HttpApplication
    {
        private static bool loop;
        public static ZmqSocket Socket { get; private set; }

        private static Logger logger;
        public static Logger Logger
        {
            get { return logger ?? (logger = LogManager.GetLogger("log")); }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            loop = true;
            RegisterRoutes(RouteTable.Routes);
            new Thread(() => StartSocket(AuctionManager.Instance.GetData)).Start();
        }

        protected void Application_End(object sender, EventArgs e)
        {
            loop = false;
            if (AuctionManager.Instance.MarketState != MarketState.Closed)
            {
                AuctionManager.Instance.CloseMarket();
            }
        }

        private static void StartSocket(Func<string> func)
        {
            try
            {
                using (var context = ZmqContext.Create())
                using (Socket = context.CreateSocket(SocketType.PUB))
                {
                    Socket.Bind("tcp://*:4444");

                    while (loop)
                    {
                        var data = func();
                        Socket.Send(data, Encoding.UTF8);
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error("Global.StartSocket：" + e.Message);
            }
        }

        private static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute("Default", "{controller}/{action}/{param}",new { controller = "Home", action = "Index", param = UrlParameter.Optional });
        }
    }
}